﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows;
using Spriter.Logic.ImageBuilder;
using Spriter.Logic.Infrastructure;
using Spriter.Ui.ViewModels;

namespace Spriter.Ui
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow
    {
        public delegate void MergeFileFinished();

        private readonly ImageBuilder _imageBuilder;
        private readonly HomeViewModel _viewModel;

        public MainWindow()
        {
            _viewModel = new HomeViewModel(GetValidFileTypes());
            _imageBuilder = new ImageBuilder();

            DataContext = _viewModel;
            InitializeComponent();

            _viewModel.FilesViewModel = FilesPicker.ViewModel;
            _viewModel.FolderViewModel = DestinationFolderPicker.ViewModel;

            InitUi();
        }

        private void InitUi()
        {
            OutputFileComboBox.SelectedIndex = 0;
        }

        private static IEnumerable<Constants.ImageType> GetValidFileTypes()
        {
            return Enum.GetValues(typeof (Constants.ImageType)).Cast<Constants.ImageType>();
        }

        private void MergeFiles(object sender, RoutedEventArgs e)
        {
            if (CheckForm())
            {
                MergeButton.IsEnabled = false;
                ErrorLabel.Visibility = Visibility.Collapsed;
                Loader.Visibility = Visibility.Visible;
                MergeFileTask();
            }
            else
            {
                ErrorLabel.Visibility = Visibility.Visible;
                SuccessLabel.Visibility = Visibility.Collapsed;
            }
        }

        private bool CheckForm()
        {
            return _viewModel.FilesViewModel.Files.Any() && !string.IsNullOrEmpty(_viewModel.OutputFilename) &&
                   !string.IsNullOrEmpty(_viewModel.FolderViewModel.FolderPath);
        }

        private void MergeFileTask()
        {
            var mergeType = GetRadioButtonValues();
            _viewModel.FilePath = GetFilepath();
            var t = new Thread(() =>
            {
                Stream stream;
                switch (mergeType)
                {
                    case Constants.SizeFormat.FixedSize:
                        stream = _imageBuilder.GenerateSpriteOrtho(_viewModel.FilesViewModel.Files);
                        break;
                    case Constants.SizeFormat.DynamicSize:
                        stream = _imageBuilder.GenerateSprite(_viewModel.FilesViewModel.Files);
                        break;
                    default:
                        return;
                }

                using (var fileStream = File.Create(_viewModel.FilePath))
                {
                    stream.Seek(0, SeekOrigin.Begin);
                    stream.CopyTo(fileStream);
                }

                Dispatcher.BeginInvoke(new MergeFileFinished(ResetMergeButton));
            });

            t.Start();
        }

        private void ResetMergeButton()
        {
            Loader.Visibility = Visibility.Collapsed;
            MergeButton.IsEnabled = true;

            SuccessLabel.Visibility = Visibility.Visible;
        }

        private Constants.SizeFormat GetRadioButtonValues()
        {
            if (ProperSizeRadioButton.IsChecked.HasValue && ProperSizeRadioButton.IsChecked.Value)
            {
                return Constants.SizeFormat.DynamicSize;
            }
            return Constants.SizeFormat.FixedSize;
        }

        private string GetFilepath()
        {
            return Path.Combine(_viewModel.FolderViewModel.FolderPath, _viewModel.OutputFilename + "." + _viewModel.OutFileType.ToString().ToLower());
        }

        private void OpenFileFolder(object sender, RoutedEventArgs e)
        {
            var runExplorer = new System.Diagnostics.ProcessStartInfo
            {
                FileName = "explorer.exe",
                Arguments = "/select, \""+GetFilepath()+"\""
            };
            System.Diagnostics.Process.Start(runExplorer);
        }
    }
}